package com.ee.chat.api.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyun.openservices.ons.api.Message;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.ee.chat.api.service.ITestService;
import com.ee.chat.api.task.HostTask;
import com.ee.chat.api.vo.OperationMessage;
import com.ee.chat.common.bean.Result;
import com.ee.chat.common.dao.*;
import com.ee.chat.common.entity.*;
import com.ee.chat.common.serconfig.MyAliOSSConfig;
import com.ee.chat.common.serconfig.MyNeteaseApp;
import com.ee.chat.common.serconfig.MyPushConfig;
import com.ee.chat.common.util.ConstantsUtil;
import com.ndhutu.ee.util.DateUtil;
import com.ndhutu.ee.util.SensitiveWordUtil;
import com.ndhutu.ee.util.netease.NeteaseUtil;
import com.ndhutu.ee.util.netease.call.Call2Util;
import com.ndhutu.ee.util.netease.im.IMUtil;
import com.ndhutu.ee.util.netease.vod.VodUtil;
import com.ndhutu.ee.util.push.jg.PushUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

@Service
public class TestServiceImpl implements ITestService {
    private Logger log = LoggerFactory.getLogger(this.getClass());

    @Resource
    UserMapper userMapper;
    @Resource
    MyNeteaseApp app;
    @Resource
    MyAliOSSConfig aliOSSConfig;
    @Resource(name = "stringRedisTemplate")
    StringRedisTemplate redisTemplate;
    @Resource
    HostMapper hostMapper;
    @Resource
    HostCallContentMapper hostCallContentMapper;
    @Resource
    HostTask hostTask;
    @Resource
    BaseMapper baseMapper;
    @Resource
    MyPushConfig pushConfig;
    @Resource
    SysPushMessageMapper sysPushMessageMapper;
    @Resource
    UserCreditLogMapper userCreditLogMapper;
    @Resource
    UserCreditExchangeLogMapper userCreditExchangeLogMapper;
    @Resource
    ExchangeConfigMapper exchangeConfigMapper;
    @Resource
    SysSensitiveWordLibMapper sysSensitiveWordLibMapper;
    @Resource
    SysKeyWordLibMapper sysKeyWordLibMapper;
    @Resource
    ProducerBean producer;
    @Resource
    UserDynamicMapper userDynamicMapper;

    @Value("${ali.rocketmq.word.topic}")
    String word_topic;
    @Value("${ali.rocketmq.word.tag1}")
    String wordTag1;
    @Value("${ali.rocketmq.word.tag2}")
    String wordTag2;

    @Override
    public Result initWord(Integer type) throws Exception {
        if(type == 0){
            List<String> words = sysSensitiveWordLibMapper.getWords();
            Map<String, Object> sensitiveWordMap = SensitiveWordUtil.init(new HashSet<>(words));

            //缓存DFA词库
            redisTemplate.opsForHash().put("data", "sensitiveWord", JSONObject.toJSONString(sensitiveWordMap));

            //生产词匹配消息
            Message message = new Message(word_topic, wordTag1, JSONObject.toJSONString(new HashMap<>()).getBytes());
            producer.sendOneway(message);
        }else if(type == 1){
            List<String> words = sysKeyWordLibMapper.getWords();
            Map<String, Object> keyWordMap = SensitiveWordUtil.init(new HashSet<>(words));

            //缓存DFA词库
            redisTemplate.opsForHash().put("data", "keyWord", JSONObject.toJSONString(keyWordMap));

            //生产词匹配消息
            Message message = new Message(word_topic, wordTag2, JSONObject.toJSONString(new HashMap<>()).getBytes());
            producer.sendOneway(message);
        }

        return Result.returnSuccess(null);
    }

    @Override
    public Result registerCall(Integer userId) throws Exception {
        User user = userMapper.selectById(userId);

        //创建user
        String ossUrl = "https://"+aliOSSConfig.getBucketName()+"."+aliOSSConfig.getEndpoint()+"/";
        String url = "https://api.netease.im/nimserver/user/create.action";
        Map<String, Object> params = new HashMap<>();
        params.put("accid", user.getId()+"");
        params.put("name", user.getName());
        params.put("icon", ossUrl+"/"+user.getIcon());
        params.put("token", user.getImToken());
        Map<String, String> headers = NeteaseUtil.getRequestHeaders(app);
        Map<String, Object> map = NeteaseUtil.post(url, params, headers);

        if(Integer.parseInt(map.get("code")+"") == 200){
            return Result.returnSuccess(null);
        }else {
            if ("already register".equals(map.get("desc"))) {
                //更新token
                url = "https://api.netease.im/nimserver/user/update.action";
                headers = NeteaseUtil.getRequestHeaders(app);
                map = NeteaseUtil.post(url, params, headers);

                if (Integer.parseInt(map.get("code") + "") != 200) {
                    throw new Exception("网易账号token更新失败");
                }

                //更新用户信息
                url = "https://api.netease.im/nimserver/user/updateUinfo.action";
                headers = NeteaseUtil.getRequestHeaders(app);

                map = NeteaseUtil.post(url, params, headers);
                if (Integer.parseInt(map.get("code") + "") != 200) {
                    throw new Exception("网易账号更新用户信息失败");
                }
            } else {
                throw new Exception(JSONObject.toJSONString(map));
            }
        }
        return Result.returnSuccess(null);
    }

    @Override
    public Result registerIM() throws Exception {
        List<User> users = userMapper.selectList(null);

        String ossUrl = "https://"+aliOSSConfig.getBucketName()+"."+aliOSSConfig.getEndpoint()+"/";

        for(User user : users){
            //创建user
            String url = "https://api.netease.im/nimserver/user/create.action";
            Map<String, Object> params = new HashMap<>();
            params.put("accid", app.getIdPrefix()+user.getId());
            params.put("name", user.getName());
            params.put("icon", ossUrl+"/"+user.getIcon());
            params.put("token", user.getImToken());
            Map<String, String> headers = NeteaseUtil.getRequestHeaders(app);
            Map<String, Object> map = NeteaseUtil.post(url, params, headers);

            if(Integer.parseInt(map.get("code")+"") == 200){
                continue;
            }else{
                if("already register".equals(map.get("desc"))){
                    //更新token
                    url = "https://api.netease.im/nimserver/user/update.action";
                    headers = NeteaseUtil.getRequestHeaders(app);
                    map = NeteaseUtil.post(url, params, headers);

                    if(Integer.parseInt(map.get("code")+"") != 200){
                        throw new Exception("网易账号token更新失败");
                    }

                    //更新用户信息
                    url = "https://api.netease.im/nimserver/user/updateUinfo.action";
                    headers = NeteaseUtil.getRequestHeaders(app);

                    map = NeteaseUtil.post(url, params, headers);
                    if(Integer.parseInt(map.get("code")+"") != 200){
                        throw new Exception("网易账号更新用户信息失败");
                    }
                }else{
                    throw new Exception(JSONObject.toJSONString(map));
                }
            }
        }

        return Result.returnSuccess(null);
    }



    @Override
    public Result deleteRoom(String cid) throws Exception {
        Call2Util.deleteRoom(cid, app);

        return Result.returnSuccess(null);
    }

    @Override
    public Result kickMembers(String cid, Integer userId) throws Exception {

        Call2Util.kickMembers(cid, app.getIdPrefix()+userId, app);

        return Result.returnSuccess(null);
    }

    @Override
    public Result updateImGender() throws Exception {
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.isNotNull("gender");
        List<User> users = userMapper.selectList(wrapper);
        log.info("需要更新性别用户数："+users.size());

        for(User user : users){
            IMUtil.updateUinfo(app.getIdPrefix()+user.getId(), null, null, user.getGender(), app);
        }
        log.info("共更新"+users.size()+"个用户性别");
        return Result.returnSuccess(null);
    }

    @Override
    public Result sendMsg() throws Exception {

        Map<String, Object> data = IMUtil.sendMsg(app.getIdPrefix()+1000000, app.getIdPrefix()+9812137, "测试", app);
        return Result.returnSuccess(data);
    }

    @Override
    public Result handleCallCentent() throws Exception {
        List<Host> hosts = hostMapper.selectList(new QueryWrapper<>());
        List<HostCallContent> calls = hostCallContentMapper.getSysCallContent();

        for(Host host : hosts){
            for(HostCallContent call : calls){
                HostCallContent hostCallContent = new HostCallContent(host.getUserId(), call.getContent(), call.getOrderId());
                hostCallContent.setStatus(1);
                hostCallContentMapper.insert(hostCallContent);
            }
        }
        return Result.returnSuccess(null);
    }

    @Override
    public Result deleteVideo(String beginTime, String endTime) throws Exception {

        int page = 1, pageSize = 300;
        List<Map<String, Object>> videos = new ArrayList<>();
        do{
            videos = VodUtil.list(page, pageSize, DateUtil.parse(beginTime), DateUtil.parse(endTime), app);

            List<Map<String, Object>> vids = new ArrayList<>();
            for(int i=1,size=videos.size(); i<=size; i++){
                vids.add(videos.get(i-1));

                if(i % 50 == 0){
                    VodUtil.delete(vids, app);
                    vids = new ArrayList<>();
                }
            }
            if(vids.size() > 0){
                VodUtil.delete(vids, app);
            }

        }while (videos.size() >= pageSize);

        return Result.returnSuccess(null);
    }

    @Override
    public Result testWebSocket(String msg, Integer userId) throws Exception {
        OperationMessage message = new OperationMessage();
        message.setUserId(123);
        message.setToUserId(456);
        redisTemplate.convertAndSend(ConstantsUtil.USER_WS_OPERATION, JSONObject.toJSONString(message));
        return Result.returnSuccess(null);
    }

    @Override
    public Result testTop1() throws Exception {
        Calendar now = Calendar.getInstance();

//        String time = DateUtil.getCurrTimeStr(DateUtil.pattern_day);
        String time = "2020-10-02 03:00:00";
        Date endTime = DateUtil.parse(time);
        Date beginTime;

        //统计日榜
        Calendar cal = Calendar.getInstance();
        cal.setTime(endTime);
        cal.add(Calendar.DAY_OF_YEAR, -1);
        beginTime = cal.getTime();
        List<Map<String, Object>> tops = userMapper.getUserCoinConsumeTop(beginTime, endTime);
        for(Map<String, Object> top : tops){
            top.put("way", 0);
            top.put("type", 0);
            top.put("createTime", now.getTime());
            top.put("beginTime", beginTime);
            top.put("endTime", endTime);
        }
        if(tops.size() > 0){
            baseMapper.batchAddUserTop(tops);
        }

        //统计周榜
        time = "2020-09-28 03:00:00";
        endTime = DateUtil.parse(time);
        cal.setTime(endTime);
        int week = cal.get(Calendar.DAY_OF_WEEK);
        if(week == 2){  //周一
            cal.setTime(endTime);
            cal.add(Calendar.DAY_OF_YEAR, -7);
            beginTime = cal.getTime();
            tops = userMapper.getUserCoinConsumeTop(beginTime, endTime);
            for(Map<String, Object> top : tops){
                top.put("way", 0);
                top.put("type", 1);
                top.put("createTime", now.getTime());
                top.put("beginTime", beginTime);
                top.put("endTime", endTime);
            }
            if(tops.size() > 0){
                baseMapper.batchAddUserTop(tops);
            }
        }

        //统计月榜
        time = "2020-10-01 03:00:00";
        endTime = DateUtil.parse(time);
        cal.setTime(endTime);
        int month = cal.get(Calendar.DAY_OF_MONTH);
        if(month == 1){  //每月1号
            cal.setTime(endTime);
            cal.add(Calendar.MONTH, -1);
            beginTime = cal.getTime();
            tops = userMapper.getUserCoinConsumeTop(beginTime, endTime);
            for(Map<String, Object> top : tops){
                top.put("way", 0);
                top.put("type", 2);
                top.put("createTime", now.getTime());
                top.put("beginTime", beginTime);
                top.put("endTime", endTime);
            }
            if(tops.size() > 0){
                baseMapper.batchAddUserTop(tops);
            }
        }
        return null;
    }

    @Override
    public Result testTop2() throws Exception {
        Calendar now = Calendar.getInstance();

//        String time = DateUtil.getCurrTimeStr(DateUtil.pattern_day);
        String time = "2020-10-02 03:00:00";
        Date endTime = DateUtil.parse(time);
        Date beginTime;

        //统计日榜
        Calendar cal = Calendar.getInstance();
        cal.setTime(endTime);
        cal.add(Calendar.DAY_OF_YEAR, -1);
        beginTime = cal.getTime();
        List<Map<String, Object>> tops = userMapper.getHostCreditTop(beginTime, endTime);
        for(Map<String, Object> top : tops){
            top.put("way", 1);
            top.put("type", 0);
            top.put("createTime", now.getTime());
            top.put("beginTime", beginTime);
            top.put("endTime", endTime);
        }
        if(tops.size() > 0){
            baseMapper.batchAddUserTop(tops);
        }

        //统计周榜
        time = "2020-09-28 03:00:00";
        endTime = DateUtil.parse(time);
        cal.setTime(endTime);
        int week = cal.get(Calendar.DAY_OF_WEEK);
        if(week == 2){  //周一
            cal.setTime(endTime);
            cal.add(Calendar.DAY_OF_YEAR, -7);
            beginTime = cal.getTime();
            tops = userMapper.getHostCreditTop(beginTime, endTime);
            for(Map<String, Object> top : tops){
                top.put("way", 1);
                top.put("type", 1);
                top.put("createTime", now.getTime());
                top.put("beginTime", beginTime);
                top.put("endTime", endTime);
            }
            if(tops.size() > 0){
                baseMapper.batchAddUserTop(tops);
            }
        }

        //统计月榜
        time = "2020-10-01 03:00:00";
        endTime = DateUtil.parse(time);
        cal.setTime(endTime);
        int month = cal.get(Calendar.DAY_OF_MONTH);
        if(month == 1){  //每月1号
            cal.setTime(endTime);
            cal.add(Calendar.MONTH, -1);
            beginTime = cal.getTime();
            tops = userMapper.getHostCreditTop(beginTime, endTime);
            for(Map<String, Object> top : tops){
                top.put("way", 1);
                top.put("type", 2);
                top.put("createTime", now.getTime());
                top.put("beginTime", beginTime);
                top.put("endTime", endTime);
            }
            if(tops.size() > 0){
                baseMapper.batchAddUserTop(tops);
            }
        }
        return null;
    }

    @Override
    public Result testTop3() throws Exception {
        Calendar now = Calendar.getInstance();

//        String time = DateUtil.getCurrTimeStr(DateUtil.pattern_day);
        String time = "2020-10-02 03:00:00";
        Date endTime = DateUtil.parse(time);
        Date beginTime;

        //统计日榜
        Calendar cal = Calendar.getInstance();
        cal.setTime(endTime);
        cal.add(Calendar.DAY_OF_YEAR, -1);
        beginTime = cal.getTime();
        List<Map<String, Object>> tops = userMapper.getHostCallTimeTop(beginTime, endTime);
        for(Map<String, Object> top : tops){
            top.put("way", 2);
            top.put("type", 0);
            top.put("createTime", now.getTime());
            top.put("beginTime", beginTime);
            top.put("endTime", endTime);
        }
        if(tops.size() > 0){
            baseMapper.batchAddUserTop(tops);
        }

        //统计周榜
        time = "2020-09-28 03:00:00";
        endTime = DateUtil.parse(time);
        cal.setTime(endTime);
        int week = cal.get(Calendar.DAY_OF_WEEK);
        if(week == 2){  //周一
            cal.setTime(endTime);
            cal.add(Calendar.DAY_OF_YEAR, -7);
            beginTime = cal.getTime();
            tops = userMapper.getHostCallTimeTop(beginTime, endTime);
            for(Map<String, Object> top : tops){
                top.put("way", 2);
                top.put("type", 1);
                top.put("createTime", now.getTime());
                top.put("beginTime", beginTime);
                top.put("endTime", endTime);
            }
            if(tops.size() > 0){
                baseMapper.batchAddUserTop(tops);
            }
        }

        //统计月榜
        time = "2020-10-01 03:00:00";
        endTime = DateUtil.parse(time);
        cal.setTime(endTime);
        int month = cal.get(Calendar.DAY_OF_MONTH);
        if(month == 1){  //每月1号
            cal.setTime(endTime);
            cal.add(Calendar.MONTH, -1);
            beginTime = cal.getTime();
            tops = userMapper.getHostCallTimeTop(beginTime, endTime);
            for(Map<String, Object> top : tops){
                top.put("way", 2);
                top.put("type", 2);
                top.put("createTime", now.getTime());
                top.put("beginTime", beginTime);
                top.put("endTime", endTime);
            }
            if(tops.size() > 0){
                baseMapper.batchAddUserTop(tops);
            }
        }
        return null;
    }

    @Override
    public Result testTop4() throws Exception {
        Calendar now = Calendar.getInstance();

//        String time = DateUtil.getCurrTimeStr(DateUtil.pattern_day);
        String time = "2020-10-02 03:00:00";
        Date endTime = DateUtil.parse(time);
        Date beginTime;

        //统计日榜
        Calendar cal = Calendar.getInstance();
        cal.setTime(endTime);
        cal.add(Calendar.DAY_OF_YEAR, -1);
        beginTime = cal.getTime();
        List<Map<String, Object>> tops = userMapper.getHostHWTop(beginTime, endTime);
        for(Map<String, Object> top : tops){
            top.put("way", 3);
            top.put("type", 0);
            top.put("createTime", now.getTime());
            top.put("beginTime", beginTime);
            top.put("endTime", endTime);
        }
        if(tops.size() > 0){
            baseMapper.batchAddUserTop(tops);
        }

        //统计周榜
        time = "2020-09-28 03:00:00";
        endTime = DateUtil.parse(time);
        cal.setTime(endTime);
        int week = cal.get(Calendar.DAY_OF_WEEK);
        if(week == 2){  //周一
            cal.setTime(endTime);
            cal.add(Calendar.DAY_OF_YEAR, -7);
            beginTime = cal.getTime();
            tops = userMapper.getHostHWTop(beginTime, endTime);
            for(Map<String, Object> top : tops){
                top.put("way", 3);
                top.put("type", 1);
                top.put("createTime", now.getTime());
                top.put("beginTime", beginTime);
                top.put("endTime", endTime);
            }
            if(tops.size() > 0){
                baseMapper.batchAddUserTop(tops);
            }
        }

        //统计月榜
        time = "2020-10-01 03:00:00";
        endTime = DateUtil.parse(time);
        cal.setTime(endTime);
        int month = cal.get(Calendar.DAY_OF_MONTH);
        if(month == 1){  //每月1号
            cal.setTime(endTime);
            cal.add(Calendar.MONTH, -1);
            beginTime = cal.getTime();
            tops = userMapper.getHostHWTop(beginTime, endTime);
            for(Map<String, Object> top : tops){
                top.put("way", 3);
                top.put("type", 2);
                top.put("createTime", now.getTime());
                top.put("beginTime", beginTime);
                top.put("endTime", endTime);
            }
            if(tops.size() > 0){
                baseMapper.batchAddUserTop(tops);
            }
        }
        return null;
    }

    @Override
    public Result pushHostMessgae(String title, String content) throws Exception {
        Map<String, String> data = new HashMap<>();
        data.put("title", title);
        data.put("content", content);
        data.put("type", "0");

        PushUtil.push("host", null, title, content, data, pushConfig);

        SysPushMessage sysPushMessage = new SysPushMessage(2, 0, title, content, JSONObject.toJSONString(data), 0);
        sysPushMessageMapper.insert(sysPushMessage);

        return null;
    }

    @Override
    public Result handleCreditExchange(String date) throws Exception {
        List<UserCreditLog> logs = userCreditLogMapper.selectByDateAndType(DateUtil.parse(date), 3);
        for(UserCreditLog log : logs){
            ExchangeConfig exchangeConfig = exchangeConfigMapper.selectByCredit(-log.getNumber());

            UserCreditExchangeLog userCreditExchangeLog = new UserCreditExchangeLog(log.getUserId(), exchangeConfig.getId(),
                    exchangeConfig.getCoin(), exchangeConfig.getCredit(), 1, log.getCreateTime());
            userCreditExchangeLogMapper.insert(userCreditExchangeLog);
        }

        return Result.returnSuccess(null);
    }

    @Override
    public Result testTimer(String timer) throws Exception {
        switch (timer){
            case "updateSuccessRate":   //更新接通率
                hostTask.updateSuccessRate();
                break;
            case "updateHostLevel":     //刷新主播等级
                hostTask.updateHostLevel();
                break;

        }

        return null;
    }

    @Override
    public Result updateLnglat(Integer type, String lnglat, Integer id) throws Exception {
        if(type == 1){
            userMapper.updateUserByLnglat(id, lnglat);
        }else if(type == 2){
            userDynamicMapper.updateLnglat(id, lnglat);
        }

        return Result.returnSuccess(null);
    }
}
